package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 生产者
 */
public class ProducerQuickStart {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //kafka链接配置信息
        Properties properties = new Properties();
        //kafka的链接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");

        //kafka的序列化
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //kafka的压缩配置
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "lz4");
//        //ack的配置，消息确认机制
//        properties.put(ProducerConfig.ACKS_CONFIG,"all");
        //创建生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        //发送消息
        //topic,key,value
//        ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>("topic-first", "key-001", "hello world");

        for (int i = 0; i < 10; i++) {
            ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>("itcast-topic-input", "hello kafka");
            producer.send(producerRecord);

        }

//        同步发送
//        RecordMetadata recordMetadata = producer.send(producerRecord).get();
//        System.out.println(recordMetadata.offset());
        //异步发送
//        producer.send(producerRecord, new Callback() {
//            @Override
//            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
//                if (e != null) {
//                    System.out.println("记录异常信息到日志表");
//                }
//                System.out.println(recordMetadata.offset());
//            }
//        });
        //关闭消息通道(必须关闭，否则消息发送不成功)
        producer.close();
    }

}
